<template>
  <div class="level-quiz">
    <div class="page-header">
      <div class="header-top">
        <button class="back-btn" @click="goToLevelDetail">← 返回关卡详情</button>
        <h1>{{ levelInfo.level_name || '关卡挑战' }}</h1>
        <div class="timer">⏱️ {{ formatTime(remainingTime) }}</div>
      </div>
      <div class="progress-indicator">
        <div class="progress-text">第 {{ currentQuestionIndex + 1 }} 题 / 共 {{ questions.length }} 题</div>
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: progressPercentage + '%' }"></div>
        </div>
      </div>
      <!-- 添加关卡进度显示 -->
      <div class="level-progress" v-if="levelProgress.total_questions > 0">
        <p>关卡进度: {{ levelProgress.answered_questions }}/{{ levelProgress.total_questions }} 题 ({{ levelProgress.accuracy_rate ? (levelProgress.accuracy_rate * 100).toFixed(1) : 0 }}% 正确率)</p>
      </div>
    </div>
    
    <div class="quiz-content" v-if="questions.length > 0 && currentQuestionIndex < questions.length">
      <div class="question-card">
        <h2>{{ currentQuestion.content }}</h2>
        <div class="options">
          <div 
            class="option" 
            v-for="option in currentQuestion.options" 
            :key="option.option_id"
            :class="{ selected: selectedOptionId === option.option_id }"
            @click="selectOption(option.option_id)"
          >
            <input 
              type="radio" 
              :id="'option' + option.option_id" 
              name="answer" 
              :value="option.option_id"
              :checked="selectedOptionId === option.option_id"
            >
            <label :for="'option' + option.option_id">{{ option.content }}</label>
          </div>
        </div>
        
        <div class="question-actions">
          <button class="prev-btn" @click="prevQuestion" :disabled="currentQuestionIndex === 0">上一题</button>
          <button 
            class="submit-btn" 
            @click="submitAnswerAndShowResult" 
            :disabled="selectedOptionId === null"
          >
            提交答案
          </button>
        </div>
      </div>
      
      <div class="quiz-info">
        <div class="info-card">
          <h3>挑战信息</h3>
          <p>📚 题目数量: {{ questions.length }}题</p>
          <p>⭐ 奖励积分: {{ levelInfo.points || 0 }}碳积分</p>
          <p>⏱️ 时间限制: {{ levelInfo.time_limit || 10 }}分钟</p>
          <!-- 添加关卡进度信息 -->
          <div class="level-info-progress" v-if="levelProgress.total_questions > 0">
            <p>🎯 已完成: {{ levelProgress.answered_questions }}/{{ levelProgress.total_questions }}</p>
            <p>✅ 正确率: {{ levelProgress.accuracy_rate ? (levelProgress.accuracy_rate * 100).toFixed(1) : 0 }}%</p>
          </div>
        </div>
      </div>
    </div>
    
    <div class="loading" v-else-if="loading">
      <p>正在加载题目...</p>
    </div>
    
    <div class="error" v-else-if="error">
      <p>加载题目失败: {{ error }}</p>
      <button class="retry-btn" @click="loadLevelQuestions">重试</button>
    </div>
    
    <div class="empty" v-else>
      <p>暂无题目信息</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getLevelDetail, submitAnswer, getLevelProgress } from '../api/challenge'

// 定义题目和选项类型
interface Option {
  option_id: number;
  content: string;
}

interface Question {
  question_id: number;
  content: string;
  options: Option[];
  explanation?: string; // 添加解析字段
}

// 定义关卡信息类型
interface LevelInfo {
  level_id: number;
  level_name: string;
  [key: string]: any;
}

// 定义关卡进度类型
interface LevelProgress {
  total_questions: number;
  answered_questions: number;
  correct_answers: number;
  accuracy_rate: number;
  [key: string]: any;
}

// 路由和路由参数
const route = useRoute()
const router = useRouter()
const levelId = computed(() => {
  const id = route.params.levelId
  return typeof id === 'string' ? parseInt(id) : 0
})

// 从查询参数获取题目索引
const questionIndexFromQuery = computed(() => {
  const index = route.query.questionIndex
  return typeof index === 'string' ? parseInt(index) : -1
})

// 数据状态
const levelInfo = ref<LevelInfo>({} as LevelInfo)
const questions = ref<Question[]>([])
// 优先使用URL参数中的题目索引，如果无效则默认为0
const currentQuestionIndex = ref(questionIndexFromQuery.value >= 0 ? questionIndexFromQuery.value : 0)
const selectedOptionId = ref<number | null>(null)
const loading = ref(true)
const error = ref('')

// 关卡进度
const levelProgress = ref<LevelProgress>({
  total_questions: 0,
  answered_questions: 0,
  correct_answers: 0,
  accuracy_rate: 0
})

// 计时器相关
const timeLimit = ref(10 * 60) // 默认10分钟
const remainingTime = ref(timeLimit.value)
let timer: number | null = null

// 计算属性
const currentQuestion = computed(() => {
  return questions.value[currentQuestionIndex.value] || { question_id: 0, content: '', options: [] } as Question
})

const progressPercentage = computed(() => {
  if (questions.value.length === 0) return 0
  return ((currentQuestionIndex.value + 1) / questions.value.length) * 100
})

// 格式化时间显示
const formatTime = (seconds: number) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 返回关卡详情页
const goToLevelDetail = () => {
  router.push(`/level-detail/${levelId.value}`)
}

// 加载关卡进度
const loadLevelProgress = async () => {
  try {
    console.log('[LevelQuiz] [DEBUG] 开始加载关卡进度:', levelId.value)
    
    // 检查levelId是否有效
    if (!levelId.value || isNaN(levelId.value)) {
      return
    }
    
    const response = await getLevelProgress(levelId.value)
    console.log('[LevelQuiz] [DEBUG] 关卡进度接口响应:', response)
    
    // 检查响应数据结构
    if (response && typeof response === 'object' && 'success' in response && response.success && 'data' in response && response.data) {
      console.log('[LevelQuiz] [DEBUG] 关卡进度数据:', response.data)
      levelProgress.value = response.data
    } else {
      console.warn('[LevelQuiz] [DEBUG] 关卡进度响应数据为空或格式不正确')
    }
  } catch (err: any) {
    console.error('[LevelQuiz] [ERROR] 加载关卡进度失败:', err)
  }
}

// 加载关卡题目
const loadLevelQuestions = async () => {
  try {
    console.log('[LevelQuiz] [DEBUG] 开始加载关卡题目:', levelId.value)
    
    // 检查levelId是否有效
    if (!levelId.value || isNaN(levelId.value)) {
      error.value = '无效的关卡ID'
      loading.value = false
      return
    }
    
    loading.value = true
    error.value = ''
    
    const response = await getLevelDetail(levelId.value)
    console.log('[LevelQuiz] [DEBUG] 关卡题目接口响应:', response)
    
    // 检查响应数据结构
    if (response && typeof response === 'object' && 'success' in response && response.success && 'data' in response && response.data) {
      console.log('[LevelQuiz] [DEBUG] 关卡题目数据:', response.data)
      
      // 修正数据结构访问方式，从 response.data.level 获取关卡信息
      const levelData = response.data.level || response.data;
      
      // 设置关卡信息
      levelInfo.value = {
        level_id: levelData.level_id,
        level_name: levelData.level_name
      }
      
      // 设置题目数据，过滤掉没有选项的题目
      questions.value = (levelData.questions || [])
        .filter((q: any) => q.options && q.options.length > 0)  // 只保留有选项的题目
        .map((q: any) => ({
          question_id: q.question_id,
          content: q.content,
          options: (q.options || []).map((opt: any) => ({
            option_id: opt.option_id,
            content: opt.content
          })),
          explanation: q.explanation || '' // 添加解析字段
        }))
      
      // 初始化题目索引
      if (questions.value.length > 0) {
        selectedOptionId.value = null
        // 如果查询参数中有题目索引，则使用该索引，否则从第一题开始
        if (questionIndexFromQuery.value >= 0 && questionIndexFromQuery.value < questions.value.length) {
          currentQuestionIndex.value = questionIndexFromQuery.value
        } else {
          currentQuestionIndex.value = 0  // 重置题目索引
        }
      } else {
        // 如果没有有效题目，显示错误信息
        error.value = '该关卡暂无有效题目'
      }
    } else {
      console.warn('[LevelQuiz] [DEBUG] 关卡题目响应数据为空或格式不正确')
      const message = typeof response === 'object' && 'message' in response ? (response as any).message : '获取关卡题目失败'
      error.value = message || '获取关卡题目失败'
      questions.value = []
    }
  } catch (err: any) {
    console.error('[LevelQuiz] [ERROR] 加载关卡题目失败:', err)
    error.value = err.message || '加载失败'
  } finally {
    loading.value = false
    console.log('[LevelQuiz] [DEBUG] 关卡题目加载完成')
  }
}

// 选择选项
const selectOption = (optionId: number) => {
  selectedOptionId.value = optionId
}

// 上一题
const prevQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
    // 重置选项选择
    selectedOptionId.value = null
  }
}

// 提交答案并显示结果
const submitAnswerAndShowResult = async () => {
  try {
    console.log('[LevelQuiz] [DEBUG] 开始提交答案')
    
    // 检查是否有选中的答案
    if (selectedOptionId.value === null) {
      showMessage('请选择一个答案','error')
      return
    }
    
    // 提交当前题目答案
    const response: any = await submitAnswer(currentQuestion.value.question_id, selectedOptionId.value)
    console.log('[LevelQuiz] [DEBUG] 提交答案响应:', response)
    
    // 检查响应是否成功（根据后端API格式）
    if (response && typeof response === 'object' && 'success' in response && response.success) {
      // 提交答案后更新关卡进度
      await loadLevelProgress()
      
      // 跳转到结果页面，传递答题结果数据和当前题目索引
      router.push({
        path: '/quiz-result',
        query: {
          levelId: levelId.value.toString(),
          questionId: currentQuestion.value.question_id.toString(),
          selectedOptionId: selectedOptionId.value.toString(),
          questionIndex: currentQuestionIndex.value.toString() // 传递当前题目索引
        }
      })
    } else {
      // 提交失败
      const message = typeof response === 'object' && 'message' in response ? response.message : '提交答案失败'
      showMessage('提交答案失败: ' + message,'error')
    }
  } catch (err: any) {
    console.error('[LevelQuiz] [ERROR] 提交答案失败:', err)
    showMessage('提交答案失败: ' + (err.message || '未知错误'),'error')
  }
}

const showMessage = (message: string, type: 'success' | 'error' = 'success') => {
  const toast = document.createElement('div')
  toast.textContent = message
  const base = 'position:fixed;left:50%;bottom:80px;transform:translateX(-50%);padding:10px 16px;border-radius:10px;color:#fff;box-shadow:0 6px 20px rgba(0,0,0,0.25);z-index:9999;font-size:14px;opacity:0.95;'
  const bg = type === 'success' ? 'background:#2E8B57;' : 'background:#E74C3C;'
  toast.setAttribute('style', base + bg)
  document.body.appendChild(toast)
  setTimeout(() => {
    toast.style.transition = 'opacity 0.3s ease'
    toast.style.opacity = '0'
    setTimeout(() => { toast.remove() }, 300)
  }, 1800)
}

// 启动计时器
const startTimer = () => {
  timer = window.setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--
    } else {
      // 时间到，自动提交当前答案（如果有选择）
      if (selectedOptionId.value !== null) {
        submitAnswerAndShowResult()
      }
      if (timer) clearInterval(timer)
    }
  }, 1000)
}

// 清理计时器
const clearTimer = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

// 组件挂载时加载数据
onMounted(() => {
  console.log('[LevelQuiz] [DEBUG] 组件挂载完成，开始加载关卡题目')
  loadLevelQuestions().then(() => {
    // 题目加载完成后加载关卡进度
    loadLevelProgress()
  })
  startTimer()
})

// 组件卸载时清理计时器
onUnmounted(() => {
  clearTimer()
})
</script>

<style scoped>
.level-quiz {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.header-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 1.8rem;
  margin: 0;
  color: #2c3e50;
  flex: 1;
  text-align: center;
  padding: 0 20px;
}

.back-btn, .timer {
  padding: 10px 20px;
  border-radius: 20px;
  font-weight: bold;
  white-space: nowrap;
}

.back-btn {
  background-color: #f8f9fa;
  color: #495057;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
}

.back-btn:hover {
  background-color: #e9ecef;
}

.timer {
  background-color: #42b983;
  color: white;
  display: flex;
  align-items: center;
  gap: 5px;
}

.progress-indicator {
  background-color: #f8f9fa;
  border-radius: 10px;
  padding: 15px;
  box-sizing: border-box;
}

.progress-text {
  text-align: center;
  margin-bottom: 10px;
  color: #495057;
  font-weight: 500;
}

.progress-bar {
  width: 100%;
  height: 12px;
  background-color: #e9ecef;
  border-radius: 6px;
  overflow: hidden;
  box-sizing: border-box;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #42b983, #2a8a64);
  border-radius: 6px;
}

/* 关卡进度样式 */
.level-progress {
  margin-top: 15px;
  padding: 10px;
  background-color: #e8f5ee;
  border-radius: 8px;
  text-align: center;
}

.level-progress p {
  margin: 0;
  color: #42b983;
  font-weight: 500;
}

.quiz-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 30px;
  max-width: 1200px;
  margin: 0 auto;
  box-sizing: border-box;
}

.question-card {
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  padding: 30px;
  box-sizing: border-box;
}

.question-card h2 {
  color: #2c3e50;
  margin-top: 0;
  margin-bottom: 30px;
  font-size: 1.5rem;
  line-height: 1.4;
}

.options {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 30px;
}

.option {
  padding: 15px 20px;
  border: 2px solid #e9ecef;
  border-radius: 10px;
  transition: all 0.3s;
  cursor: pointer;
}

.option:hover {
  border-color: #42b983;
  background-color: #f8f9fa;
}

.option.selected {
  border-color: #42b983;
  background-color: #e8f5ee;
}

.option input {
  margin-right: 15px;
}

.option label {
  cursor: pointer;
  font-size: 1.1rem;
  color: #495057;
}

.option input:checked + label {
  font-weight: bold;
  color: #2c3e50;
}

.option input:checked {
  accent-color: #42b983;
}

.question-actions {
  display: flex;
  justify-content: space-between;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.prev-btn, .submit-btn {
  padding: 12px 30px;
  border: none;
  border-radius: 25px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.prev-btn {
  background-color: #f8f9fa;
  color: #495057;
}

.prev-btn:hover:not(:disabled) {
  background-color: #e9ecef;
}

.prev-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.submit-btn {
  background-color: #42b983;
  color: white;
}

.submit-btn:hover:not(:disabled) {
  background-color: #359c6d;
  transform: scale(1.05);
}

.submit-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quiz-info {
  align-self: start;
}

.info-card {
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  padding: 25px;
  box-sizing: border-box;
}

.info-card h3 {
  margin-top: 0;
  color: #2c3e50;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.info-card p {
  margin: 15px 0;
  color: #6c757d;
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 关卡信息中的进度样式 */
.level-info-progress p {
  margin: 10px 0;
  padding: 8px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.loading, .error, .empty {
  text-align: center;
  padding: 40px 20px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.loading p, .error p, .empty p {
  margin: 0;
  color: #6c757d;
  font-size: 1.1rem;
}

.retry-btn {
  background-color: #ff6b35;
  color: white;
  padding: 10px 20px;
  border-radius: 20px;
  font-weight: bold;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 15px;
}

.retry-btn:hover {
  background-color: #e55a2b;
  transform: scale(1.05);
}

@media (max-width: 768px) {
  .quiz-content {
    grid-template-columns: 1fr;
  }
  
  .page-header h1 {
    font-size: 1.5rem;
    padding: 0 10px;
  }
  
  .question-card {
    padding: 20px;
  }
  
  .question-card h2 {
    font-size: 1.3rem;
  }
  
  .option {
    padding: 12px 15px;
  }
  
  .option label {
    font-size: 1rem;
  }
  
  .question-actions {
    flex-direction: column;
    gap: 15px;
  }
  
  .prev-btn, .submit-btn {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .level-quiz {
    padding: 15px;
  }
  
  .page-header {
    padding: 15px;
  }
  
  .header-top {
    flex-direction: column;
    gap: 15px;
  }
  
  .page-header h1 {
    font-size: 1.3rem;
    padding: 0;
  }
  
  .back-btn, .timer {
    padding: 8px 15px;
    font-size: 0.9rem;
  }
  
  .question-card {
    padding: 15px;
  }
  
  .info-card {
    padding: 20px;
  }
}
</style>
